import express from 'express';
import { readConfig, writeConfig, getConfigFilePath } from '../storage.js';

const router = express.Router();

router.get('/', (req, res) => {
  const cfg = readConfig();
  res.json({
    hasKey: Boolean(cfg.apiKey),
    baseUrl: cfg.baseUrl || '',
    defaultModel: cfg.defaultModel || '',
    _configFile: getConfigFilePath(),
  });
});

router.post('/', (req, res) => {
  const { apiKey, baseUrl, defaultModel } = req.body || {};

  if (apiKey !== undefined && typeof apiKey !== 'string') {
    return res.status(400).json({ error: 'apiKey 必须为字符串' });
  }
  if (baseUrl !== undefined && typeof baseUrl !== 'string') {
    return res.status(400).json({ error: 'baseUrl 必须为字符串' });
  }
  if (defaultModel !== undefined && typeof defaultModel !== 'string') {
    return res.status(400).json({ error: 'defaultModel 必须为字符串' });
  }

  const saved = writeConfig({ apiKey, baseUrl, defaultModel });
  res.json({ ok: true, hasKey: Boolean(saved.apiKey) });
});

export default router;


